package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate> list = new ArrayList<>();
        list.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            list.add(begin);
        }
        ArrayList<Double> turnoverList = new ArrayList<>();
        // 遍历得到的每一个日期
        for (LocalDate localDate : list) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            // 根据当天日期的开始时间和结束时间，以及订单状态已完成条件查询所有订单总金额
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            // 订单总金额
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
//            if (turnover == null) {
//                turnover = 0.0;
//            }
            turnoverList.add(turnover);
        }
        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
                .dateList(StringUtils.join(list,","))
                .turnoverList(StringUtils.join(turnoverList))
                .build();
        return turnoverReportVO;
    }

    /**
     * 用户统计接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        // 首先要得到每一天的日期，封装成list集合
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        // 想要获得用户总量和新增用户
        // 新增用户
        ArrayList<Integer> newUserList  = new ArrayList<>();
        // 用户总量totalUserList
        ArrayList<Integer> totalUserList  = new ArrayList<>();
        // 首先得到每一天的开始和结束时间
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            // 根据用户的注册时间和每一天的开始、结束时间比较来查询已注册的用户
            Map map = new HashMap();
            map.put("end",endTime);
            Integer totalUser = userMapper.getUserCount(map);
            totalUserList.add(totalUser);

            map.put("begin",beginTime);
            Integer newUser = userMapper.getUserCount(map);
            newUserList.add(newUser);
        }
        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }

    /**
     * 订单统计接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        // 首先要得到每一天
        ArrayList<LocalDate> datelist = new ArrayList<>();
        datelist.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            datelist.add(begin);
        }

        // 每日订单数集合
        ArrayList<Integer> orderCountList = new ArrayList<>();
        // 每日有效订单数集合
        ArrayList<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : datelist) {
            // 获取到每日的开始和结束时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);

            Integer number = orderMapper.countByMap(map);
            orderCountList.add(number);
            map.put("status",Orders.COMPLETED);
            Integer count = orderMapper.countByMap(map);
            validOrderCountList.add(count);
        }
        // 订单总数
        Integer totalOrderCount = 0;
        for (int i = 0; i < orderCountList.size(); i++) {
            totalOrderCount = orderCountList.get(i) + totalOrderCount;
        }
        // 有效订单数
        Integer validOrderCount = 0;
        for (int i = 0; i < validOrderCountList.size(); i++) {
            validOrderCount = validOrderCount + validOrderCountList.get(i);
        }
        // 订单完成率
        Double orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(datelist,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 查询销量排名top10接口k
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        // 要得到已完成订单时间日期在begin和end范围内的所有订单中的菜品数量
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getTop10(beginTime,endTime);
        // 创建一个商品名称集合
        ArrayList<String> nameList = new ArrayList<>();
        // 创建一个销量列表的集合
        ArrayList<Integer> numberList = new ArrayList<>();
        for (GoodsSalesDTO goodsSalesDTO : goodsSalesDTOList) {
            String name = goodsSalesDTO.getName();
            nameList.add(name);
            Integer number = goodsSalesDTO.getNumber();
            numberList.add(number);
        }
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        // 1、查询数据库，获取营业的数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        LocalDateTime begin = LocalDateTime.of(dateBegin, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(dateBegin, LocalTime.MAX);
        // 查询概览数据
        BusinessDataVO businessData = workspaceService.getBusinessData(begin,end);
        // 2、通过POI将数据写入到excel文件中
        // 先获得一个表格对象
        // 获取输入流对象
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            // 基于模板文件来创建一个excel文件
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            // 填充数据  时间
            XSSFSheet sheet = excel.getSheet("Sheet1");
            // 已有模板中已有行，所以不用创建行了，可以直接去获取行填充数据
            // 获取模板中的第二行第二个单元，并且填充数据
            sheet.getRow(1).getCell(1).setCellValue("时间："+dateBegin + "--"+dateEnd);

            // 获取第四行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            // 获取第五行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            // 填充明细数据
            // 遍历30次，得到每一天
            for (int i = 0; i < 30; i++) {
                dateBegin = dateBegin.plusDays(1);
                LocalDateTime beginDate = LocalDateTime.of(dateBegin, LocalTime.MIN);
                LocalDateTime endDate = LocalDateTime.of(dateBegin, LocalTime.MAX);
                // 查询某一天的营业数据
                BusinessDataVO businessData1 = workspaceService.getBusinessData(beginDate, endDate);
                // 开始填充数据
                row = sheet.getRow(i + 7);
                row.getCell(1).setCellValue(dateBegin.toString());
                row.getCell(2).setCellValue(businessData1.getTurnover());
                row.getCell(3).setCellValue(businessData1.getValidOrderCount());
                row.getCell(4).setCellValue(businessData1.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData1.getUnitPrice());
                row.getCell(6).setCellValue(businessData1.getNewUsers());
            }
            // 3、通过输出流将excel文件下载到客户端浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);

            // 关闭资源
            outputStream.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
